package silentDonkey.web.servlet;

import org.apache.commons.beanutils.BeanUtils;
import silentDonkey.domain.Admin;
import silentDonkey.service.UserService;
import silentDonkey.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.设置编码
        request.setCharacterEncoding("utf-8");
        // 2.获取数据
        // 2.1获取用户填写的验证码
        String verifyCode = request.getParameter("verifyCode");
        // 3.验证码校验
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER"); // 确保验证码一次性
        if (!verifyCode.equalsIgnoreCase(checkcode_server)) {
            // 验证码不正确->提示信息
            request.setAttribute("loginMsg", "验证码不正确");
            // 跳转到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        // 获取所有请求参数
        Map<String, String[]> map = request.getParameterMap();
        // 4.封装管理员Admin对象
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 5.调用Service查询
        UserService service = new UserServiceImpl();
        Admin loginAdmin = service.login(admin);
        // 6.判断是否登录成功
        if (loginAdmin != null) {
            // 登录成功->将用户存入session,重定向到主页
            session.setAttribute("admin", loginAdmin);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            // 登陆失败->提示用户名或密码错误，跳转登录页面
            request.setAttribute("loginMsg", "用户名或密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
